﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using S7.Net;

namespace PLC
{
    public class PLCS7Manager
    {

        private static String ip = "192.168.2.1";
        private static int rack = 0;
        private static int slot = 1;
        private static ushort connectionType = 3;

        static PLCS7Manager pLCS7Manager = null;
        static Plc plc = null;
        private bool isConnected =false;



        private PLCS7Manager()
        {

        }

        public static PLCS7Manager GetInstance(String ip, int rack, int slot, ushort connectionType)
        {
            PLCS7Manager.ip = ip;
            PLCS7Manager.rack = rack;
            PLCS7Manager.slot = slot;
            PLCS7Manager.connectionType = connectionType;

            if (plc == null)
            {
                plc = new Plc(CpuType.S71200, ip, (short)rack, (short)slot);
                pLCS7Manager = new PLCS7Manager();
            }
            return pLCS7Manager;
        }


        public int Connect()
        {
            if (isConnected)
            {
                return 0;
            }

            plc.Open();
            isConnected = true;
            return 0;
        }

        public void Close()
        {
            if (isConnected)
            {
                plc.Close();
                isConnected = false;
            }
        }

        public float readVData(String address)
        {
             return (float)plc.Read(address);


        }


        public float readVDataV1(int dataBlock, int db, int start, int count)
        {
            //plc.ReadBytes()

            return  (float)plc.Read((DataType)dataBlock, db, start, VarType.Real, 1);
            //return BitConverter.ToSingle(new byte[] { data[0], data[1], data[2], data[3] }, 0);

        }

        public float readVData(int dataBlock,int db ,int start,int count)
        {
            //plc.ReadBytes()
            
            byte[] data = plc.ReadBytes((DataType)dataBlock, db,start, count);
            return BitConverter.ToSingle(new byte[] { data[0], data[1], data[2], data[3] }, 0);
            
        }

       
    }
}
